package com.guguju.ssms.feature.Home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.blankj.utilcode.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonObject;
import com.guguju.ssms.Guguju;
import com.guguju.ssms.R;
import com.guguju.ssms.bean.LoginData;
import com.guguju.ssms.bean.UserDayProject;
import com.guguju.ssms.bean.UserDayProjectData;
import com.guguju.ssms.bean.VoidBack;
import com.guguju.ssms.constant.IntentParms;
import com.guguju.ssms.constant.UrlConstant;
import com.guguju.ssms.core.base.BaseFragment;
import com.guguju.ssms.core.http.HttpLoader;
import com.guguju.ssms.core.log.LogUtil;
import com.guguju.ssms.feature.login.LoginActivity;
import com.guguju.ssms.widget.ErrorView;
import com.guguju.ssms.widget.common.AdapterLoadMoreView;

import java.util.ArrayList;
import java.util.List;

import com.guguju.ssms.core.http.BaseResponse;
import com.guguju.ssms.core.http.HttpLoader;
import com.guguju.ssms.core.http.JsonCallback;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by dell on 2022-5-14.
 */
public class IndexFragment  extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener,  SwipeRefreshLayout.OnRefreshListener {
    private HomeActivity activity;

    RecyclerView rvIndex;
    SwipeRefreshLayout swipeRefreshLayout;
    ImageButton btnBackTop;
    LinearLayout ll_progress;
    //分页使用变量
    private boolean isRefresh = true;
    private int start = 0;
    private static final int NUM = 5;

    private indexAdapte adapter;
    private ArrayList<UserDayProject> data = new ArrayList<>();
    /**
     * fragment name
     */
    public static final String TAG = IndexFragment.class.getName();
    /**
     * 使用静态工厂方法newInstance(...)来获取Fragment实例
     *
     * @return fragment instance
     */
    public static IndexFragment newInstance() {
        LogUtil.i(TAG + "   create");
        IndexFragment indexFragment = new IndexFragment();
        return indexFragment;
    }

    private int tempUserId = 0;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_index;
    }

    @Override
    protected void afterCreate() {
        activity = (HomeActivity) getActivity();
        ll_progress=getView().findViewById(R.id.ll_progress);
        btnBackTop=getView().findViewById(R.id.btn_index_back_to_top);;
        swipeRefreshLayout = getView().findViewById(R.id.srfl_index);
        rvIndex= getView().findViewById(R.id.rv_index);
        if(Guguju.USERID<=0) {
            if (!Guguju.isOpenLoginActivity) {
                Guguju.isOpenLoginActivity = true;
                if (Guguju.applicationContext != null) {
                    Intent intent = new Intent(Guguju.applicationContext, LoginActivity.class);
                    intent.putExtra(IntentParms.LOGIN_FROM, IntentParms.LOGIN_FROM_HTTPLOAD);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Guguju.applicationContext.startActivity(intent);
                }
            }
        }
        swipeRefreshLayout.setOnRefreshListener(this);
        adapter = new indexAdapte( getContext(),data);
        adapter.setOnLoadMoreListener(this, rvIndex);
        adapter.setLoadMoreView(new AdapterLoadMoreView());

        rvIndex.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvIndex.setHasFixedSize(true);
        rvIndex.setAdapter(adapter);


        btnBackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btnBackTop.setVisibility(View.GONE);
                rvIndex.scrollToPosition(0);
            }
        });




        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {

                switch (view.getId()) {
                    case R.id.bt_dayproject_complete:
                        UserDayProject dayProject=data.get(position);
                        doDayProjectComplete(dayProject.getDayProjectId());
                        //ToastUtils.showShortToast(getContext(), "点击了tv_dayprojectType");

                        break;
                }
            }
        });


        rvIndex.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int lastVisibleItemPosition = 0;
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager) {
                    lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                }

                if (lastVisibleItemPosition > 3) {
                    btnBackTop.setVisibility(View.VISIBLE);
                } else {
                    btnBackTop.setVisibility(View.GONE);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

        });

        getDateList();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (data.size() == 0 || tempUserId!= Guguju.USERID) {
            tempUserId =  Guguju.USERID;
            onRefresh();
        }
    }


    @Override
    public void onLoadMoreRequested() {
        isRefresh = false;
        start += NUM;
        getDateList();
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        start = 0;
        getDateList();
    }



    /**
     * 获取用户数据
     */
    private void getDateList() {
        Guguju.applicationContext=getContext();
        swipeRefreshLayout.setRefreshing(true);
        final JsonObject params = HttpLoader.getBaseHttpParams();
        params.addProperty("first", start);
        params.addProperty("selectStatus", 1);
        params.addProperty("rows", NUM);

        HttpLoader.post(UrlConstant.GET_USER_DAYPROJECT, params, true, new JsonCallback<BaseResponse<UserDayProjectData>>() {

            @Override
            public void onSuccess(BaseResponse<UserDayProjectData> userDayProjectDataBaseResponse, Call call, Response response) {
                swipeRefreshLayout.setRefreshing(false);

                if (userDayProjectDataBaseResponse.data != null && userDayProjectDataBaseResponse.data.getUserDayProjectList() != null && userDayProjectDataBaseResponse.data.getUserDayProjectList().size() > 0) {
                    List<UserDayProject> newData = userDayProjectDataBaseResponse.data.getUserDayProjectList();
                    if (isRefresh) {
                        rvIndex.scrollToPosition(0);
                        data.clear();
                        data.addAll(newData);
                        adapter.setNewData(newData);
                    } else {
                        data.addAll(newData);
                        adapter.addData(newData);
                        adapter.loadMoreComplete();
                    }

                    if (newData.size() < NUM) {
                        adapter.loadMoreEnd();
                    }
                } else {
                    if (isRefresh) {
                        data.clear();
                        ErrorView errorView = new ErrorView(getContext());
                        errorView.setType(ErrorView.TYPE_SHANGPIN);
                        adapter.setEmptyView(errorView);
                        adapter.setNewData(data);
                    } else {
                        adapter.loadMoreEnd();
                    }
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                if (!isRefresh) {
                    adapter.loadMoreFail();
                }
                swipeRefreshLayout.setRefreshing(false);
                super.onError(call, response, e);
            }
        });
    }


    /**
     * 发送短信请求
     */
    public void doDayProjectComplete(final int dayProjectId) {
        //ll_progress.setVisibility(View.VISIBLE);
        final JsonObject params = HttpLoader.getBaseHttpParams();
        params.addProperty("dayProjectId", dayProjectId);

        HttpLoader.post(UrlConstant.USER_DODAYPROJECT_COMPLETE, params, true, new JsonCallback<BaseResponse<VoidBack>>() {

            @Override
            public void onSuccess(BaseResponse<VoidBack> BaseResponse, Call call, Response response) {
               // ll_progress.setVisibility(View.GONE);
                if (BaseResponse.code == 200) {
                    getDateList();
                    ToastUtils.showShortToast(getActivity(),BaseResponse.msg);
                }
                else
                {
                    ToastUtils.showShortToast(getActivity(), BaseResponse.msg);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
               // ll_progress.setVisibility(View.GONE);
                ToastUtils.showShortToast(getActivity(), e.getMessage());
            }
        });
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        //unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //unbinder.unbind();
    }



}
